package smart
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	import flash.utils.getQualifiedSuperclassName;
	
	import smart.mediator.Mediator;

	public class ViewMap  extends CoreConnector
	{
		 
	
		protected var context:DisplayObjectContainer;
		public function ViewMap()
		{
			context=context;
			
		}
		
		public function generateView(view:Class):DisplayObject
		{
			var v:Sprite=new view();
			v.addEventListener(Event.ADDED_TO_STAGE,onAddToStage);
			return v;
		}
		/**
		 * Element is added to context,let's generate mediator for him 
		 * @param e
		 * 
		 */		
		public function onViewAdded(e:Event):void
		{
			var className:String=getQualifiedClassName(e.target);
			var cls:Class=getDefinitionByName(className) as Class;
			injector.mapValueToClass(cls,e.target);
			var InjectedMediaClass:String=injector.getInjectedView(className) as String;
			if(InjectedMediaClass)
			{
				var MediaClass:Class=getDefinitionByName(InjectedMediaClass) as Class;
				if(MediaClass)
				{
					var mediator:Mediator=new MediaClass();
					//mediator.view=e.target as DisplayObject;
					mediator.onRegister();
				}
			
			}
		}
		public function setContext(context:DisplayObjectContainer):void
		{
			context.addEventListener(Event.ADDED_TO_STAGE, onViewAdded, false, 0, true);
		}
		
		public function mapView(view:Class,mediater:Class):void
		{
			injector.mapView(view,mediater);
		}
		private function onAddToStage(e:Event):void
		{
			var element:DisplayObject=e.target as DisplayObject;
			element.removeEventListener(Event.ADDED_TO_STAGE,onAddToStage);
			element.dispatchEvent(new  Event(Event.ADDED_TO_STAGE,true));
		}
	}
}